<!--用车申请页-->
<template>
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">申请单列表</span>
    <el-button type="primary" style="float:right;margin-top:13px;" @click="addApplication">请假申请</el-button>
  </div>

  <!-- 用车申请列表 搜索卡片 -->
  <el-card style="margin: 20px;">
    <el-form style="padding-top:10px;">
      <el-row :gutter="30">
        <el-col :span="5">
          <el-form-item label="申请人姓名">
            <el-input placeholder="请输入姓名" v-model="username"
                      @click="loadApplication"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="请假申请状态">
            <el-select placeholder="请选择" v-model="status">
              <el-option v-for="item in applicationStatusOptions" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="loadApplication">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>

  <!-- 用车申请表格 -->
  <el-card style="margin:20px">
    <el-table :data="applicationListArr">
      <el-table-column type="index" width="80" align="center" prop="id" label="编号"></el-table-column>
      <el-table-column align="center" prop="username" label="申请人"></el-table-column>
      <el-table-column align="center" prop="reason" label="请假原因"></el-table-column>
      <el-table-column align="center" prop="type" label="请假类型" :formatter="applicationTypeFormatter"></el-table-column>
      <el-table-column align="center" prop="auditUsernameList" label="审批人"></el-table-column>
      <el-table-column align="center" prop="stime" label="请假开始时间"></el-table-column>
      <el-table-column align="center" prop="etime" label="请假结束时间"></el-table-column>
      <el-table-column align="center" prop="status" label="申请单状态" :formatter="applicationStatusFormatter"></el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" link :disabled="scope.row.status!=10" @click="cancel(scope.row.id)">撤销</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 请假申请弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" style="width:1000px;padding:40px;"
             :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="申请人">
            <el-input readonly :value="saveApplicationForm.username"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="请假时间">
            <el-date-picker
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                v-model="times"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="请假原因">
            <el-input placeholder="请输入" type="textarea" resize="none" :rows="3"
                      v-model="saveApplicationForm.reason"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input placeholder="请输入" type="textarea" resize="none" :rows="3"
                      v-model="saveApplicationForm.rmark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="请假类型">
            <el-select placeholder="请选择" v-model="saveApplicationForm.type">
              <el-option v-for="item in applicationTypeArr"
                         :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上传材料">
            <el-upload
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审批人">
            <el-row :gutter="10">
                  <el-col :span="12" v-if="auditUserOpts.length > 0">
                    <el-tag type="primary">
                      <el-icon style="margin-right:5px;position:relative;top:2px;">
                        <User/>
                      </el-icon>
                      <span>{{ auditUserOpts[0].username }}</span>
                    </el-tag>
                  </el-col>
                  <el-col :span="12" v-if="auditUserOpts.length > 1">
                    <el-tag type="primary">
                      <el-icon style="margin-right:5px;position:relative;top:2px;">
                        <User/>
                      </el-icon>
                      <span>{{ auditUserOpts[1].username }}</span>
                    </el-tag>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveStaffApplication">确定</el-button>
    </template>
  </el-dialog>




</template>
<script setup>
import {onMounted, ref} from "vue";
import axios from "/src/api/axios";
import {ElMessage} from "element-plus";
import qs from "qs";

//定义变量控制创建申请单弹窗是否出现
const dialogVisible = ref(false);
//定义变量用来控制弹窗的标题
const dialogTitle = ref('新建表单');


//获取当前登录的用户信息（目前获取不到）
const user = ref(getUser());
//定义数组用来保存新增申请表单中的审批人(含姓名)
const auditUserOpts = ref([]);
//定义数组用来保存新增申请单时,对应的审批人id,入库使用
const auditUserIdList = ref([]);

//定义加载审批人的方法(未实现)

//定义员工部门数组来维护员工所属部门的选项,重置和查询那里
const staffDepOptions = ref([
  {label: '部门1', value: '10'},
  {label: '部门2', value: '20'},
  {label: '部门3', value: '30'},
  {label: '部门4', value: '40'}
]);

//定义数组用来保存请假申请单的状态,重置和查询那里
const applicationStatusOptions = ref([
  {label: "已发起", value: "10"},
  {label: '撤销', value: '20'},
  {label: '审核中', value: '30'},
  {label: '驳回', value: '40'},
  {label: '已通过', value: '50'},
]);


//对申请单状态显示内容进行文字转换
const applicationStatusFormatter = (row,column,cellValue,index)=>{
  if(cellValue == 10){
    cellValue = '已发起';
  }else if(cellValue == 20){
    cellValue = '撤销';
  }else if(cellValue == 30){
    cellValue = '审核中';
  }else if(cellValue == 40){
    cellValue = '驳回';
  }else if(cellValue == 50){
    cellValue = '已通过';
  }
  return cellValue;
}


//定义数组用来保存展示的请假申请表格数据,卡片里表格的数据
const applicationListArr = ref([
  //员工姓名，请假原因，请假开始时间,请假结束时间，申请单状态,审批人
  // {username:'aaa',reason:'1111111111',startTime:'2024-07-01',endTime:'2024-07-02',status:'已发起',auditUsernameList:'tom'},
  // {username:'bbb',reason:'1111111111',startTime:'2024-07-01',endTime:'2024-07-02',status:'已发起',auditUsernameList:'bob'},
  // {username:'ccc',reason:'1111111111',startTime:'2024-07-01',endTime:'2024-07-03',status:'已通过',auditUsernameList:'tom'},
  // {username:'ddd',reason:'1111111111',startTime:'2024-07-02',endTime:'2024-07-03',status:'驳回',auditUsernameList:'bob'},
  // {username:'eee',reason:'1111111111',startTime:'2024-07-02',endTime:'2024-07-04',status:'已通过',auditUsernameList:'tom'},
  // {username:'fff',reason:'1111111111',startTime:'2024-07-03',endTime:'2024-07-05',status:'驳回',auditUsernameList:'bob'},
  // {username:'hhh',reason:'1111111111',startTime:'2024-07-03',endTime:'2024-07-06',status:'已通过',auditUsernameList:'tom'},
]);

//定义数组变量保存请假类型,点击新建申请,弹窗里的请假类型
const applicationTypeArr = ref([
  //事假,病假,出差
  {label: '事假', value: '10'},
  {label: '病假', value: '20'},
  {label: '出差', value: '30'},
]);

//对请假类型显示内容进行文字转换
const applicationTypeFormatter = (row,column,cellValue,index)=>{
  if(cellValue == 10){
    cellValue = '事假';
  }else if(cellValue == 20){
    cellValue = '病假';
  }else if(cellValue == 30){
    cellValue = '出差';
  }
  return cellValue;
}


//处理弹窗关闭的方法
const handleClose = () => {
  if (confirm('确认要关闭本窗口吗?')) {
    //用户确认关闭后,关闭弹窗
    dialogVisible.value = false;
    //清空已输入的表单数据
    saveApplicationForm.value = {};
  }
}

/* 点击"新建申请"按钮，出弹窗+修改弹窗标题 */
const addApplication = () => {
  dialogTitle.value = '新建请假申请';
  dialogVisible.value = true;
}

//定义对象来保存用户查询的条件 申请人姓名,申请人部门,请假申请状态
const searchApplicationForm = ref({username: '', status: '', });
const currentPage = ref(1);
const pageSize = ref(5);
const totals = ref(0);

//定义加载请假申请列表的方法
const loadApplication = () => {
  const searchPage = ref({
    currentPage: currentPage.value,
    pageSize:  pageSize.value,
    username: username.value,
    status: status.value,
  });
  axios.post('http://localhost:8092/application/page',searchPage.value).then((response) => {//回调函数,处理响应数据
    totals.value = response.data.totals;
    applicationListArr.value = response.data.data;
    console.log(applicationListArr.value);
  })
}

//定义对象来保存用户查询的条件
const username = ref('');
const status = ref('');

const handleCurrentChange = (c) =>{
  currentPage.value = c;
  loadApplication();
}
const handleSizeChange = (d) =>{
  pageSize.value = d;
  loadApplication();
}

//定义变量用来保存表单中的"使用时间",注意:这是一个数组，包含开始时间与结束时间
const times = ref([]);

//定义对象保存弹窗表单新增或修改考勤数据
const saveApplicationForm = ref({
  reason: '',//请假理由
  rmark: '',//备注
  type: ''  //请假类型 事假,病假,出差
});

//定义方法发送新增申请单请求
//* 点击弹窗中的“保存员工请假申请”按钮 => 新增+更新员工请假申请 */
const saveStaffApplication = () => {
  if(fileList.value.length==0){
    ElMessage.error('请上传图片!');
    return;
  }
  //从upload图片上传组件中获取上传图片的路径 fileList.value[0]表示第一张图片对象
  saveApplicationForm.value.imgUrl = fileList.value[0].response.data;//驾照图片路径
  //saveApplicationForm.value.uid = user.value.id;//申请人id
  //saveApplicationForm.value.username = user.value.username;//申请人姓名
  saveApplicationForm.value.stime = times.value[0];//开始时间
  saveApplicationForm.value.etime = times.value[1];//结束时间
  // 注意:审批人id数据也需要一起给到后端,因为事务性新增,审批表的数据也需要一起更新!
  // addForm.value.auditUserIdList = auditUserIdList.value;//审批人id集合
  console.log(saveApplicationForm.value);
  axios.post("/application/save",saveApplicationForm.value,{serviceName:'workService'}).then((response)=>{
    if (response.data.code == 2000){
      ElMessage.success('保存成功!');
      dialogVisible.value = false;//关闭弹窗
      fileList.value = [];//清空图片上传组件
      times.value = [];//清空时间选择器组件
      saveApplicationForm.value={};//清空其他4个表单项
      //新增成功后需要重新加载申请数据
      loadApplication();
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}

//撤销用车申请
const cancel = (id) => {
  axios.post('http://localhost:8092/application/cancel/'+id).then((response)=>{
    if (response.data.code==2000){
      ElMessage.success('撤销成功!');
      //更新完当前申请单状态后,也需要重新加载申请单数据
      loadApplication();
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

//重置搜索
const resetSearch = () => {
  //清空之前的搜索内容
  username.value='';
  status.value='';
  //重新加载所有的用户请假申请数据
  loadApplication();
}

//页面一加载完毕,立即执行
onMounted(() => {
  loadApplication();
})

/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref('http://localhost:8092' + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post('http://localhost:8092' + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true;
  console.log(uploadFile);
  //console.log(fileList.value[0].response.data);
}
/**图片上传相关代码结束**/

</script>

<style scoped>
</style>